package cc.web.vaaking.servlet;

import cc.web.vaaking.common.AjaxResult;
import cc.web.vaaking.common.AjaxTool;
import cc.web.vaaking.common.LoginUser;
import cc.web.vaaking.common.RequestContext;
import cc.web.vaaking.common.utils.ValueUtils;
import cn.hutool.log.StaticLog;
import com.github.pagehelper.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public abstract class BaseHttpServlet extends HttpServlet {
    protected Map<String, BiConsumer<HttpServletRequest, HttpServletResponse>> routerMap = new HashMap<>();

    @Override
    public abstract void init() throws ServletException;

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestContext.begin(this.getServletContext(), req, resp);
        super.service(req, resp);
        pageHelper(req);
        req.setCharacterEncoding("utf-8");
        String route = req.getRequestURI().replace(req.getContextPath() + req.getServletPath() + "/", "");
        BiConsumer<HttpServletRequest, HttpServletResponse> router = routerMap.get(route);//路由转发
        if (router == null) {
            router = (requst, response) -> {
                StaticLog.warn("{}: No route {}", this.getClass().getTypeName(), req.getRequestURI());
            };
            if ("GET".equals(req.getMethod())) {
                resp.sendRedirect(req.getContextPath() + "/views/error/404.jsp");
            } else {
                AjaxTool.returnAjax(resp, AjaxResult.error("404"));
            }
        } else {

            String query = req.getQueryString();
            StringBuilder sb = new StringBuilder(query == null ? "" : "?" + query);
            StaticLog.info("{} {} {}", this.getClass().getCanonicalName(), req.getMethod(), req.getRequestURI() + sb.toString());
        }
        router.accept(req, resp);
    }


    protected void pageHelper(HttpServletRequest req) {
        int pageNum = Integer.parseInt(ValueUtils.getParamOrDefault(req, "pageNum", "1"));
        int pageSize = Integer.parseInt(ValueUtils.getParamOrDefault(req, "pageSize", "10"));
        String orderBy = ValueUtils.getParamOrDefault(req, "orderBy", "");
        PageHelper.startPage(pageNum, pageSize,orderBy);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
